import 'package:casdon/modules/recipe/data/model/recipe_module_model.dart';
import 'package:casdon/modules/recipe/domain/states/recipe_module_list_state.dart';
import 'package:casdon/modules/recipe/providers/recipe_provider.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class RecipeModuleListNotifier extends AsyncNotifier<RecipeModuleListState> {
  bool _isRefreshing = false;

  @override
  Future<RecipeModuleListState> build() async {
    return _fetchData();
  }

  Future<void> refresh() async {
    if (_isRefreshing) return;
    _isRefreshing = true;

    try {
      final newState = await _fetchData();
      state = AsyncValue.data(newState);
    } finally {
      _isRefreshing = false;
    }
  }

  Future<RecipeModuleListState> _fetchData() async {
    final previous = state.valueOrNull;

    try {
      final ret = await ref.read(recipeModuleListUsecaseProvider).execute();
      final data = RecipeModuleModel.listFromApi(ret)
        ..sort((a, b) => a.sort.compareTo(b.sort));

      return RecipeModuleListState(data: data);
    } catch (_) {
      return previous ?? RecipeModuleListState.initial();
    }
  }
}
